#include <stdio.h>

#include "SDL/SDL_log.h"
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "sprite.h"

#define WINDOW_HEIGHT 800
#define WINDOW_WIDHT 600

SDL_Window *window;
SDL_Renderer *render;

Sprite* sprite;

void draw(){
    //使用render绘制白色背景
    SDL_SetRenderDrawColor(render, 255, 255, 255, 255);
    SDL_RenderClear(render);

    //开始绘制
    if(sprite == NULL){
       createSprite(&sprite, render, 0, 200);
    }
    showSprite(sprite, render);
  //  destroySprite(sprite2);
    //结束绘制

    SDL_RenderPresent(render);
    SDL_UpdateWindowSurface(window);
}

void event_loop(){
 //必须有事件处理，否则窗体出不来，
    while (1)
    {
       draw();
       SDL_Event event;
       while(SDL_PollEvent(&event)){
           // printf("event is %#x\n", event.type); // test code
            switch (event.type)
            {
                case SDL_MOUSEMOTION:

                   SDL_Log("move...%d", event.motion.x);
                   sprite->posX = event.motion.x;
                   sprite->posY = event.motion.y;
                   break;
                case SDL_MOUSEBUTTONDOWN:
                   sprite->posX = event.button.x;
                   sprite->posY = event.button.y;
                   break;
                case SDL_MOUSEBUTTONUP:
                   break;      
                case SDL_QUIT:
                    return;
                
                default:
                    break;
            }
            if (SDL_QUIT == event.type) {
                return;
            }
       }
    }
}

int showWindow(){
    if(SDL_Init(SDL_INIT_VIDEO)){
       SDL_Log("init error : %s", SDL_GetError());
       return 1;
    }
    window = SDL_CreateWindow("title", 
                            SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                            WINDOW_WIDHT, WINDOW_HEIGHT, SDL_WINDOW_SHOWN);
    if(window == NULL){
       SDL_Log("create window error %s", SDL_GetError());
       return 2;
    }

    //创建图形渲染器
    render = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    if(render == NULL){
       SDL_Log("create render error %s", SDL_GetError());
    }
    //事件循环
    event_loop();
    
    SDL_DestroyRenderer(render);
    SDL_DestroyWindow(window);
}

int main()
{
    showWindow();
    return 0;
}